<template>
  <div class="form_content">
    <el-dialog
      v-model="diaShow"
      :close-on-click-modal="false"
      :title="dialogTitle"
      width="40%"
      :before-close="handleClose"
    >
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="120px">
        <el-form-item label="活动名称：" prop="activityName">
          <el-input
            v-model="form.activityName"
            show-word-limit
            maxlength="15"
            :disabled="form.isLook"
            clearable
            type="primary"
            link
            placeholder="请输入渠道名称"
          />
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input
            v-model="form.remark"
            maxlength="200"
            :disabled="form.isLook"
            clearable
            type="primary"
            link
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="活动时间：" prop="startTime">
          <el-date-picker
            v-model="activityTimeArr"
            :disabled="form.isLook"
            range-separator="至"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="活动发放数量：" prop="publishCount">
          <el-input-number
            v-model="form.publishCount"
            :disabled="form.isLook"
            :controls="false"
            :max="999999999"
            :min="1"
          /> &emsp;份
        </el-form-item>
        <el-form-item label="发放渠道券" prop="couponList">
          <el-button
            :disabled="form.isLook"
            type="primary"
            @click="showCouponSelect"
          >请选择
          </el-button>
        </el-form-item>
        <el-form-item label=" ">
          <el-table
            :data="form.couponList"
            border
            :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column label="优惠券名称" width="220">
              <template #default="scope">{{ scope.row.couponName }}</template>
            </el-table-column>
            <el-table-column label="类型" show-overflow-tooltip>
              <template #default="scope">
                <span v-if="scope.row.couponType === 1">满减券</span>
                <span v-if="scope.row.couponType === 2">折扣券</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" show-overflow-tooltip>
              <template #default="scope">
                <span v-if="scope.row.state === 0">未开始</span>
                <span v-if="scope.row.state === 1">进行中</span>
                <span v-if="scope.row.state === 2">已结束</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="content"
              label="内容"
              show-overflow-tooltip
            />
            <el-table-column
              prop="createTime"
              label="创建时间"
              show-overflow-tooltip
            />
            <el-table-column label="操作" fixed="right">
              <template #default="scope">
                <el-button
                  type="danger"
                  :disabled="form.isLook"
                  @click="handleDelSelectCoupon(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <template v-if="!form.isLook" #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button :loading="loading" type="primary" @click="handleConfirm">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <SelectChannelCoupons
      v-model="showSelect"
      :default-selection="form.couponList"
      :take-end="form.endTime"
      :stock-number="form.publishCount"
      @confirm="handleSelectChannelCoups"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, toRefs } from 'vue'
import SelectChannelCoupons from './selectChannelCoupons.vue'
import { useVModel } from '@vueuse/core'
import { add, edit, getCouponsByActivityId } from '@/api/channelActivity'
const Form = function () {
  this.id = null
  this.activityName = null
  this.remark = null
  this.startTime = null
  this.endTime = null
  this.publishCount = null
  this.couponList = []
  this.isLook = false
}

const validateCouponList = (rule, value, callback) => {
  if (form.value.couponList.length <= 0) {
    callback(new Error('请选择渠道优惠券'))
    return
  }
  callback()
}

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  item: {
    type: [Object, null],
    default: () => ({
      id: null,
      name: null
    })
  }
})
const { item } = toRefs(props)
const emits = defineEmits(['update:modelValue', 'confirm', 'close'])
const diaShow = useVModel(props, 'modelValue', emits)
const formRef = ref(null)
const loading = ref(false)
const dialogTitle = ref('新增渠道券活动')
const form = ref({
  id: null,
  activityName: null,
  remark: null,
  startTime: null,
  endTime: null,
  publishCount: null,
  couponList: [],
  isLook: false
})
const formRules = {
  activityName: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    {
      min: 1,
      max: 15,
      message: '活动名称长度在1-15个字符',
      trigger: 'blur',
    },
  ],
  startTime: [
    { required: true, message: '请选择活动时间', trigger: 'blur' },
  ],
  publishCount: [
    { required: true, message: '请输入活动发放数量', trigger: 'blur' },
  ],
  couponList: [{ validator: validateCouponList, trigger: 'blur' }],
}
// 是否显示选择券
const showSelect = ref(false)
const activityTimeArr = computed({
  get () {
    if (!form.value.startTime || !form.value.endTime) return []
    return [form.value.startTime, form.value.endTime]
  },
  set (val) {
    if (!val) {
      form.value.startTime = null
      form.value.endTime = null
      return
    }
    form.value.startTime = val[0]
    form.value.endTime = val[1]
  }
})

watch(item, (newVal) => {
  if (newVal.id) {
    if (newVal.isLook) {
      dialogTitle.value = '渠道券活动详情'
    } else {
      dialogTitle.value = '修改渠道券活动'
    }
    form.value = JSON.parse(JSON.stringify(newVal))
  } else {
    dialogTitle.value = '新增渠道券活动'
    form.value = new Form()
    handleResetForm()
  }
}, { deep: true })
watch(diaShow, (newVal) => {
  if (item.value.id && newVal) {
    handleGetCouponsByActivityId()
  }
})

const showCouponSelect = () => {
  if (!form.value.startTime || !form.value.endTime) {
    ElMessage.warning('请先选择活动时间')
    return
  }
  showSelect.value = true
}
const handleSelectChannelCoups = (s) => {
  console.log(s)
  form.value.couponList = s
}
const handleDelSelectCoupon = (i) => {
  const { couponList } = form.value
  const spliceIndex = couponList.findIndex(
    (e) => e.shopCouponId === i.shopCouponId
  )
  couponList.splice(spliceIndex, 1)
}
const handleConfirm = () => {
  if (form.value.isLook) {
    diaShow.value = false
    handleResetForm()
    form.value.couponList = []
    return
  }
  formRef.value.validate(async (valid) => {
    if (!valid) return ElMessage.error('请完善表单')
    loading.value = true
    form.value.couponList.forEach((i) => {
      i.couponId = i.shopCouponId
    })
    try {
      if (form.value.id) {
        form.value.couponList.forEach((i) => {
          i.id = form.value.id
        })
        // 修改
        await edit(form.value)
      } else {
        await add(form.value)
      }
    } finally {
      loading.value = false
    }
    ElMessage.success('操作成功')
    diaShow.value = false
    handleResetForm()
    form.value.couponList = []
    emits('confirm', form.value)
  })
}
// 获取活动优惠券
const handleGetCouponsByActivityId = async () => {
  const { data } = await getCouponsByActivityId({
    channelActivityId: form.value.id,
    page: 1,
    pageSize: 10000,
  })
  form.value.couponList = data.list
}
const handleClose = () => {
  handleResetForm()
  emits('close', form.value)
  form.value.couponList = []
  diaShow.value = false
}
const handleResetForm = () => {
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.form_content {
}
</style>
